// pages/discount/CouponDetails.js
var Zan = require('../../dist/index.js');
var QQMapWX = require('../../utils/qqmap-wx-jssdk.min.js');
let WxNotificationCenter = require('../../utils/WxNotificationCenter.js');
let network = null;
let utils = null;
let api = null;
const app = getApp();
let constants = null;
var start = 0;
Page(Object.assign({}, Zan.TopTips, Zan.Toast, {

  /**
   * 页面的初始数据
   */
  data: {
    couponId: '',
    lat: '',
    lng: '',
    coupon: {},
    stores: [],
    users: [],
    couponList: [],
    isGet: 0,
    userStatus: false,
    moretxt: '查看更多优惠券'
  },

  /** 
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    network = new app.NetWorkUtils();
    utils = new app.Utils();
    api = new app.Api();

    this.setData({
      couponId: options.couponId
    })


    constants = new app.Constants();
    var that = this;
    wx.getLocation({
      type: 'wgs84',
      success: function (res) {
        let latitude = res.latitude
        let longitude = res.longitude
        wx.request({
          url: `https://apis.map.qq.com/ws/geocoder/v1/?location=${latitude},${longitude}&key=${constants.key}`,
          success: res => {
            console.log(res);
            let location = res.data.result.ad_info;
            that.setData({
              lng: res.data.result.location.lng,
              lat: res.data.result.location.lat,
              province: location.province,
              city: location.city,
              district: location.district
              // region: [location.province, location.city, location.district]
            })
            that.onPullDownRefresh()
          }
        })
      }
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    wx.stopPullDownRefresh();
    start = 0;
    this.setData({
      stores: [],
      users: [],
      couponList: [],
      isGet: 0
    })
    network._post_json(this, api.couponDetails, { couponId: this.data.couponId, lat: this.data.lat, lng: this.data.lng }, success);
    network._post_request(this, api.couponDetailsMore, start, 5, { couponId: this.data.couponId }, MoreSuccess);

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    var that = this;
    return {
      title: that.data.coupon.name,
      path: '/pages/discount/CouponDetails?couponId=' + that.data.coupon.id,
      success: function (res) {
      },
      fail: function (res) {
        // 转发失败
      }
    }
  },

  // moreCoupon:function(e){
  //   var brandId = e.currentTarget.dataset.id;
  //   var status = e.currentTarget.dataset.status;
  //   var name = e.currentTarget.dataset.name;
  //   wx.navigateTo({
  //     url: '/pages/discount/BrandCoupon' + '?brandId=' + brandId + '&status=' + status + '&name=' + encodeURIComponent(name)
  //   })
  // },


  moreCouponList: function (e) {
    if (this.data.couponList.length < this.data.recordsTotal - 1) {
      start = start + 5;
      network._post_request(this, api.couponDetailsMore, start, 5, { couponId: this.data.couponId }, MoreSuccess);
    } else {
      this.setData({
        moretxt: '暂无更多'
      })
    }
  },

  goMap: function (e) {
    //114.35663,30.52636
    var lat = e.currentTarget.dataset.lat;
    var lng = e.currentTarget.dataset.lng;
    wx.openLocation({
      type: 'wgs84 ',
      latitude: lat,
      longitude: lng,
      scale: 18
    });
  },
  goCouponUser: function (e) {
    var id = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: '/pages/discount/CouponUser' + '?couponId=' + id,
    })
  },
  getCoupon: function (e) {
    var brandId = e.currentTarget.dataset.id;
    network._post_json(this, api.couponRece, { couponId: this.data.couponId, brandId: brandId }, getSuccess);
  },
  useCoupon: function (e) {
    var id = e.currentTarget.dataset.id;
    var status = e.currentTarget.dataset.status;
    wx.navigateTo({
      url: '/pages/myself/coupon/UseCoupon' + '?couponId=' + id,
    })
  },
  moreListDetail: function (e) {
    var id = e.currentTarget.dataset.id;
    wx.redirectTo({
      url: '/pages/discount/CouponDetails' + '?couponId=' + id,
    })
  }
}))
var success = function (that, res) {
  res.data.data.startTime = utils.formatDate02(new Date(res.data.data.startTime))
  res.data.data.endTime = utils.formatDate02(new Date(res.data.data.endTime))
  for (let j = 0; j < res.data.data.stores.length; j++) {
    res.data.data.stores[j].openTime = utils.formatDate03(new Date(res.data.data.stores[j].openTime))
    res.data.data.stores[j].closeTime = utils.formatDate03(new Date(res.data.data.stores[j].closeTime))
  }

  if (res.data.data) {
    that.setData({
      coupon: res.data.data,
      stores: that.data.stores.concat(res.data.data.stores),
      isGet: res.data.data.isGet,
      users: that.data.users.concat(res.data.data.users).slice(0, 3),
    })
  }
}
var getSuccess = function (that, res) {
  console.log(res);
  if (res.data.data) {
    that.setData({
      isGet: 1
    })
    that.onPullDownRefresh();
    WxNotificationCenter.postNotificationName("RefreshMyselfCount");
  }
}
var MoreSuccess = function (that, res) {
  for (let j = 0; j < res.data.data.length; j++) {
    res.data.data[j].startTime = utils.formatDate02(new Date(res.data.data[j].startTime))
    res.data.data[j].endTime = utils.formatDate02(new Date(res.data.data[j].endTime))
  }
  if (res.data.data) {
    that.setData({
      couponList: that.data.couponList.concat(res.data.data),
      recordsTotal: res.data.recordsTotal
    })
  }
}